package com.example.java.base.concurrency.threadpool;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * A9PauseableThreadPool:演示每个任务执行前后放钩子函数
 *
 * @author zhangxiaoxiang
 * @date 2020/11/5
 */
@Slf4j
public class A9PauseableThreadPool extends ThreadPoolExecutor {
    /**
     * 加锁(可重入)
     */
    private final ReentrantLock lock = new ReentrantLock();
    /**
     * 不暂停-返回与此Lock实例一起使用的Condition实例
     */
    private Condition unpaused = lock.newCondition();
    /**
     * 暂停(标记位)
     */
    private boolean isPaused;

    /**
     * 示例只用这个即可作为创建此线程池
     * @param corePoolSize 核心线程数
     * @param maximumPoolSize 最大线程数
     * @param keepAliveTime 线程活跃时间
     * @param unit 单位
     * @param workQueue 队列
     */
    public A9PauseableThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime,
                                 TimeUnit unit,
                                 BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }

    // public A9PauseableThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime,
    //                              TimeUnit unit, BlockingQueue<Runnable> workQueue,
    //                              ThreadFactory threadFactory) {
    //     super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
    // }
    //
    // public A9PauseableThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime,
    //                              TimeUnit unit, BlockingQueue<Runnable> workQueue,
    //                              RejectedExecutionHandler handler) {
    //     super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);
    // }
    //
    // public A9PauseableThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime,
    //                              TimeUnit unit, BlockingQueue<Runnable> workQueue,
    //                              ThreadFactory threadFactory, RejectedExecutionHandler handler) {
    //     super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory,
    //             handler);
    // }

    @Override
    protected void beforeExecute(Thread t, Runnable r) {
        super.beforeExecute(t, r);
        //获取锁
        log.info("任务执行前获取锁,类似于AOP前置增强一样");
        lock.lock();
        try {
            while (isPaused) {
                unpaused.await();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //释放锁
            lock.unlock();
            log.info("任务执行后释放锁,类似于AOP后置增强一样");
        }
    }

    /**
     * 暂停
     */
    private void pause() {
        lock.lock();
        try {
            isPaused = true;
            log.info("pause暂停标记为--->{}",isPaused);
        } finally {
            lock.unlock();
            log.info("pause暂停释放锁--->{}",isPaused);
        }
    }

    /**
     * 恢复
     */
    public void resume() {
        lock.lock();
        try {
            isPaused = false;
            unpaused.signalAll();
            log.info("resume唤醒所有等待的线程,并将暂停按钮设置为--->{}",isPaused);
        } finally {
            lock.unlock();
            log.info("resume唤醒所有等待的线程,释放锁");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        //自定义线程池
        A9PauseableThreadPool a9PauseableThreadPool = new A9PauseableThreadPool(
                10,
                20,
                10L,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>());
        Runnable runnable = () -> {
            log.info("我被执行");
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };
        for (int i = 0; i < 10000; i++) {
            a9PauseableThreadPool.execute(runnable);
        }
        Thread.sleep(1500);
        a9PauseableThreadPool.pause();
        log.info("线程池被暂停了");
        Thread.sleep(1500);
        a9PauseableThreadPool.resume();
        log.info("线程池被恢复了");

    }
}
